package com.shanghai.shanghaielectric.UI;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.shanghai.shanghaielectric.Constants;
import com.shanghai.shanghaielectric.R;
import com.shanghai.shanghaielectric.UI.refreshView.MyAdapter_updateAPP;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import shanghaielectric_lib.Utils.LogUtil;


/**
 * 更新apk界面
 */
@SuppressLint("NewApi")
public class UpdateApkFragment extends Fragment {
    @BindView(R.id.check)
    Button check;
    @BindView(R.id.update)
    Button update;
    Unbinder unbinder;
    @BindView(R.id.usb_state)
    TextView usbState;
    private View updateApkView;
    private Context mContext;
    private LayoutInflater myInflater;
    private int pause = 0;
    RecyclerView list;
    MyAdapter_updateAPP myAdapter_updateAPP;
    UsbBroadCastReceiver usbBroadCastReceiver;
    public List<File> listFiles;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        System.out.println("UpdateApkFragment____onAttach");
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        System.out.println("UpdateApkFragment____onCreate");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        System.out.println("UpdateApkFragment____onCreateView");
        updateApkView = inflater.inflate(R.layout.updateapk_fragment, container, false);
        mContext = getActivity().getApplicationContext();
        pause = 0;
        unbinder = ButterKnife.bind(this, updateApkView);
        usbBroadCastReceiver = new UsbBroadCastReceiver();
        registerUsbReceiver();
        listFiles = new ArrayList<>();

        list = (RecyclerView) updateApkView.findViewById(R.id.applist);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(mContext);
        list.setLayoutManager(layoutManager);
        myAdapter_updateAPP = new MyAdapter_updateAPP(mContext, listFiles);
        list.setAdapter(myAdapter_updateAPP);
        getApk();
        setUsbStateListener(usbStateListener);

        return updateApkView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        System.out.println("UpdateApkFragment____onActivityCreated");
    }

    @Override
    public void onStart() {
        super.onStart();
        System.out.println("UpdateApkFragment____onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
        if (pause == 1) {
            pause = 0;
//			initData();
        }
        System.out.println("UpdateApkFragment____onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        pause = 1;
        System.out.println("UpdateApkFragment____onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        System.out.println("UpdateApkFragment____onStop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        System.out.println("UpdateApkFragment____onDestroyView");
        unbinder.unbind();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mContext.unregisterReceiver(usbBroadCastReceiver);
        System.out.println("UpdateApkFragment____onDestroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        System.out.println("UpdateApkFragment____onDetach");
    }

    @OnClick({R.id.check, R.id.update})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.check:
//                getApk();
                break;
            case R.id.update:
                break;
        }
    }

    public static class UsbBroadCastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Constants.USB_PATH = intent.getData().getPath();
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_MEDIA_CHECKING)) {
                Toast.makeText(context, "正在检查U盘，请稍后", Toast.LENGTH_LONG).show();

                if (mUsbStateListener != null) {
                    mUsbStateListener.onchange("CHECKING");
                }
            } else if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
                //USB设备移除，更新UI
                if (mUsbStateListener != null) {
                    mUsbStateListener.onchange("OUT");
                }
//                Toast.makeText(MyApplication.getContext(), "usb移除", Toast.LENGTH_SHORT).show();
            } else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
//                Toast.makeText(MyApplication.getContext(), "usb插入", Toast.LENGTH_SHORT).show();
                //USB设备挂载，更新UI
                if (mUsbStateListener != null) {
                    mUsbStateListener.onchange("IN");
                }
                LogUtil.e("UsbBroadCastReceiver===", intent.getData().getPath());
            }
        }
    }

    private void registerUsbReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
        filter.addAction(Intent.ACTION_MEDIA_CHECKING);//插入广播，正在检查
        filter.addAction(Intent.ACTION_MEDIA_EJECT);
        filter.addAction(Intent.ACTION_MEDIA_REMOVED);//移除
        // 必须要有此行，否则无法收到广播
        filter.addDataScheme("file");
        mContext.registerReceiver(usbBroadCastReceiver, filter);
    }

    interface UsbStateListener {
        void onchange(String code);
    }

    public static UsbStateListener mUsbStateListener;

    public static void setUsbStateListener(UsbStateListener usbStateListener) {
        mUsbStateListener = usbStateListener;
    }

    public UsbStateListener usbStateListener = new UsbStateListener() {
        @Override
        public void onchange(String code) {
//            Toast.makeText(mContext, "收到" + flag, Toast.LENGTH_SHORT).show();
            switch (code) {
                case "IN":
                    getApk();
                    break;
                case "OUT":
                    usbState.setText("U盘已移除");
                    getApk();
                    break;
                case "CHECKING":
                    usbState.setText("U盘已插入，正在检测");
                    break;
            }
        }
    };


    public void getApk() {

        File f = new File(Constants.USB_PATH);
        final String[] files_name = f.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.startsWith("上海");
            }
        });
        listFiles.clear();
        if (files_name != null && files_name.length > 0) {


            for (int i = 0; i < files_name.length; i++) {
//            Toast.makeText(mContext, "apk" + files_name[i], Toast.LENGTH_SHORT).show();
                listFiles.add(new File(Constants.USB_PATH + File.separator + files_name[i]));
                usbState.setText("检测完成");
            }

        }
        myAdapter_updateAPP.notifyDataSetChanged();
    }
}
